﻿using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.UI;
using AjaxChatWebApp.DTO;

namespace AjaxChatWebApp.Account
{
    public partial class Login : Page
    {
        HttpClient httpClient = new HttpClient();
        protected void Page_Load(object sender, EventArgs e)
        {
            httpClient.BaseAddress = new Uri("http://localhost:62865");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        protected void tbLogin_Click(object sender, EventArgs e)
        {
            string userName = tbUserName.Text;
            string password = tbPassword.Text;
            var user = GetUser(userName, password);
            if(user != null)
            {
                user.Status = true;
                Session["IsLogin"] = true;
                Session["UserId"] = user.Id;
                Session["UserName"] = user.UserName;
                Response.Redirect("~/Default.aspx");
            }
            else
            {
                FailureText.Text = "Invalid username or password";
            }
        }

        private User GetUser(string userName, string password)
        {
            User user = null;
            string url = "api/users?userName=" + userName + "&password=" + password;
            HttpResponseMessage response = httpClient.GetAsync(url).Result;
            if(response.IsSuccessStatusCode)
            {
                user = response.Content.ReadAsAsync<User>().Result;
            }
            return user;
        }

        protected void btYhLogin_Click(object sender, EventArgs e)
        {
            string username = tbYhUserName.Text;
            string password = tbYhPassword.Text;

            string url = "api/YMUsers?username=" + username + "&password=" + password;
            HttpResponseMessage response = httpClient.GetAsync(url).Result;
            if(response.IsSuccessStatusCode)
            {
                Session["YMUsername"] = username;
                Response.Redirect("~/YahooMessengerPage.aspx");
            }
            else
            {
                FailureText.Text = "Yahoo! Messenger login failure";
            }
        }

        protected void btFbLogin_Click(object sender, EventArgs e)
        {
            string username = tbYhUserName.Text;
            string password = tbYhPassword.Text;

            string url = "api/FBUsers?username=" + username + "&password=" + password;
            HttpResponseMessage response = httpClient.GetAsync(url).Result;
            if (response.IsSuccessStatusCode)
            {
                Session["FBUsername"] = username;
                Response.Redirect("~/FacebookChatPage.aspx");
            }
            else
            {
                FailureText.Text = "Facebook chat login failure";
            }
        }
    }
}